var express = require('express');
var router = express.Router();

var {execSql} = require('./db/mysql')


router.all('/f1',async function(req, res, next) {
  var taskid = req.body.taskid
  var sql =taskid.length==0||taskid == undefined?
   'select * from hyx_app_mockapi order by id desc;':
   'select * from hyx_app_mockapi where taskid=\''+taskid +'\' order by id desc;'
  var ret = await execSql(sql)
  if(ret){
    res.send(ret)
  }else{
    res.send([])
  }
});

router.all('/f2', async function(req, res, next) {
  var sql0 ='select count(*) from hyx_app_mockapi where url=\''+req.body.url +'\' and appid =\''+req.body.appid+'\';';
  var ret0 = await execSql(sql0)
  var count = ret0[0]["count(*)"]
  if(count == 0){
    var sql = 'insert into hyx_app_mockapi (appid, taskid, url,para,resp) VALUES (';
    sql = sql+'\''+req.body.appid+'\',';
    sql = sql+'\''+req.body.taskid+'\',';
    sql = sql+'\''+req.body.url+'\',';
    sql = sql+'\''+req.body.req+'\',';
    sql = sql+'\''+req.body.resp+'\');';
    var ret = await execSql(sql)
    if(ret){
      res.send({state:0,msg:'成功'})
    }else{
      res.send({state:1,msg:'失败'})
    }
  }else{
    res.send({state:1,msg:'请勿重复添加'})
  }
});

router.all('/f3', async function(req, res, next) {
  var sql = "delete from hyx_app_mockapi where id = \'"+req.body.id+'\'';
  var ret = await execSql(sql)
  if(ret){
    res.send({
      state:0,
      message:'查询成功'
    });
  }else{
    res.send({
      state:1,
      message:'查询失败'
    });
  }
});

router.all('/f4', async function(req, res, next) {
  var id = req.body.id; 
  var sql = 'select * from hyx_app_mockapi where id =\''+id+'\'';
  var ret = await execSql(sql)
  var resp = ret[0]?ret[0]:ret
  if(resp){
    res.send({
      state:0,
      result: resp,
      message:'查询成功'
    });
  }else{
    res.send({
      state:1,
      result:{},
      message:'查询失败'
    });
  }
});

router.all('/update', async function(req, res, next) {
  var sql = 'update hyx_app_mockapi set taskid=\''+req.body.taskid+'\',url=\''+req.body.url+'\',resp=\''+req.body.resp+ '\'where id =\''+req.body.id+'\'';
  var ret = await execSql(sql)
  if(ret){
    res.send({
      state:0,
      message:'更新成功'
    });
  }else{
    res.send({
      state:1,
      message:'更新失败'
    });
  }
});

router.all('/:reqid',async function (req,res,next) {
  var reqid = req.params.reqid; 
  var sql = 'select resp from hyx_app_mockapi where url =\''+reqid+'\'';
  var ret = await execSql(sql)
  var resp = ret[0]?ret[0]:ret,
  resp = resp.resp;
  if(resp){
    res.send({
      state:0,
      result: JSON.parse(resp),
      message:'查询成功'
    });
  }else{
    res.send({
      state:1,
      result:{},
      message:'查询失败'
    });
  }
})

module.exports = router;
